#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPushButton>
#include <QListWidget>
#include <QLabel>
#include <QBluetoothDeviceDiscoveryAgent>
#include <QBluetoothServiceDiscoveryAgent>
#include <QBluetoothLocalDevice>
#include <QLowEnergyController>
#include <QLineEdit>

#include "BluetoothDeviceCell.h"

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void SlotSearchButtonClicked();
    void SlotDeviceDiscovered(const QBluetoothDeviceInfo &info);
    void SlotDeviceSearchFinished();
    void SlotDeviceSearchErrorOccurred();

    void SlotServiceDiscovered(const QBluetoothServiceInfo &info);
    void SlotServiceSearchFinished();

    void SlotDeviceListWidgetItemActivated(QListWidgetItem *deviceItem);
    void SlotServiceListWidgetItemActivated(QListWidgetItem *serviceItem);

    void serviceDiscovered(const QBluetoothServiceInfo & info);


    void SlotLowEnergyControllerConnected();
    void SlotLowEnergyControllerDisconnected();
    void SlotLowEnergyControllerServiceDiscovered(const QBluetoothUuid &newService);
    void SlotLowEnergyControllerDiscoveryFinished();
    void SlotLowEnergyControllerError(QLowEnergyController::Error);

    void ConnectService(QString uuid);
    void SlotLowEnergyServiceError(QLowEnergyService::ServiceError newErrorr);
    void SlotLowEnergyServiceStateChanged(QLowEnergyService::ServiceState newState);
    void SlotLowEnergyServiceCharacteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue);
    void SlotLowEnergyServiceDescriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue);

    void SlotReadButtonClicked();
    void SlotWriteButtonClicked();
private:
    void Init();

private:
    QPushButton *searchButton{ nullptr };
    QLabel *statusLabel{ nullptr };
    QListWidget *deviceListWidget{ nullptr };
    QListWidget *serviceListWidget{ nullptr };
    QListWidget *characterListWidget{ nullptr };

    QLineEdit *serviceEdit{ nullptr };
    QPushButton *serviceButton{ nullptr };
    QLineEdit *readEdit{ nullptr };
    QPushButton *readButton{ nullptr };
    QLineEdit *writeEdit{ nullptr };
    QPushButton *writeButton{ nullptr };

    QPushButton *cancelButton{ nullptr };
    QPushButton *connectButton{ nullptr };

    QBluetoothDeviceDiscoveryAgent *deviceDiscoveryAgent{ nullptr };
    QLowEnergyController *lowEnergyController{ nullptr };

    QList<QBluetoothDeviceInfo> deviceInfoList;
    QList<QBluetoothUuid> bluetoohUuids;
    QList<QBluetoothUuid> servicesUuids;
    QList<QLowEnergyCharacteristic> characters;
};

#endif // WIDGET_H
